<?php

class Avatar_AdminAvatarcollectionController extends Core_Controller_Action_Admin {
	public function browseAction() {
		$this->view->navigation = $navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'avatar_admin_main', array (), 'avatar_admin_main_avatarcollection' );
		$this->view->collections = $collections = Engine_Api::_ ()->getDbtable ( 'avatarcollections', 'avatar' )->fetchAll ( 'name desc' );
		if (count ( $collections )) {
			if (! $collection_id = $this->_getParam ( 'collection_id' )) {
				$this->view->current_collection = $current_collection = $collections->current ();
				$collection_id = $current_collection->avatarcollection_id;
			} else {
				if (($this->view->current_collection = $collections->getRowMatching ( 'avatarcollection_id', $collection_id )) == null) {
					$this->_forward ( 'requiresubject', 'error', 'core' );
					return;
				}
			}
			$this->view->avatars = $avatars = Engine_Api::_ ()->getDbtable ( 'avatars', 'avatar' )->fetchAll ( array ('avatarcollection_id = ?' => $collection_id ) );
			$this->view->form = $form = new Avatar_Form_Admin_Avatarcollections_Avatar ();
			$form->set_collection_id ( $collection_id );
		}
	
	}
	
	public function newCollectionAction() {
		// In smoothbox
		$this->_helper->layout->setLayout ( 'admin-simple' );
		
		// Generate and assign form
		$form = $this->view->form = new Avatar_Form_Admin_Avatarcollections_Avatarcollections ();
		if ($this->_hasParam ( 'collection_id' )) {
			$avatarcollectionsRow = Engine_Api::_ ()->getDbtable ( 'avatarcollections', 'avatar' )->fetchRow ( array ('avatarcollection_id = ?' => $this->_getParam ( 'collection_id' ) ) );
			$form->populate ( $avatarcollectionsRow->toArray () )->setTitle ( 'Edit Avatar Collection' );
			$edit = true;
		} else {
			$form->setTitle ( 'Add Avatar Collection' );
			$edit = false;
		}
		if ($this->getRequest ()->isPost () && $form->isValid ( $this->getRequest ()->getPost () )) {
			$avatarcollections = Engine_Api::_ ()->getDbtable ( 'avatarcollections', 'avatar' );
			// Begin database transaction
			$db = $avatarcollections->getAdapter ();
			$db->beginTransaction ();
			
			try {
				
				$values = $form->getValues ();
				if (! $edit)
					$avatarcollectionsRow = $avatarcollections->createRow ();
				$avatarcollectionsRow->setFromArray ( $values );
				$avatarcollectionsRow->save ();
				if (! $edit) {
					$dirdest = APPLICATION_PATH . '/application/modules/Avatar/externals/avatarcollections/' . $avatarcollectionsRow->avatarcollection_id;
					if (! mkdir ( $dirdest ))
						throw new Engine_Exception ( "Cann't create directory: $dirdest. Permission denied." );
				}
				$db->commit ();
				$this->_forward ( 'success', 'utility', 'core', array ('parentRefresh' => 1500, 'messages' => ($edit) ? array ('Avatar Collection was saved.' ) : array ('Avatar Collection was created.' ) ) );
			} 

			catch ( Exception $e ) {
				$db->rollBack ();
				throw $e;
			}
		
		} else
			$this->renderScript ( 'admin-avatarcollection/form.tpl' );
	}
	
	public function deleteAction() {
		// In smoothbox
		$this->_helper->layout->setLayout ( 'admin-simple' );
		$this->view->delete_title = 'Delete Collection?';
		$this->view->delete_description = 'Are you sure you want to delete this Collection and all avatars in it? It will not be recoverable after this.';
		$id = $this->_getParam ( 'collection_id' );
		$this->view->collection_id = $id;
		// Check post
		if ($this->getRequest ()->isPost ()) {
			$db = Engine_Db_Table::getDefaultAdapter ();
			$db->beginTransaction ();
			
			try {
				$slide = Engine_Api::_ ()->getDbtable ( 'avatarcollections', 'avatar' )->fetchRow ( array ('avatarcollection_id = ?' => $id ) );
				$slide->delete ();
				
				$db->commit ();
				$dir = APPLICATION_PATH . '/application/modules/Avatar/externals/avatarcollections/' . $id;
				if (is_dir ( $dir )) {
					$objects = scandir ( $dir );
					foreach ( $objects as $object ) {
						if ($object != "." && $object != "..") {
							unlink ( $dir . "/" . $object );
						}
					}
					reset ( $objects );
					rmdir ( $dir );
				}
			} 

			catch ( Exception $e ) {
				$db->rollBack ();
				throw $e;
			}
			
			$this->_forward ( 'success', 'utility', 'core', array ('smoothboxClose' => 10, 'parentRefresh' => 10, 'messages' => array ('' ) ) );
		}
		
		// Output
		$this->renderScript ( 'etc/delete.tpl' );
	}
	
	public function deleteAvatarAction() {
		// In smoothbox
		$this->_helper->layout->setLayout ( 'admin-simple' );
		$this->view->delete_title = 'Delete Avatar?';
		$this->view->delete_description = 'Are you sure you want to delete this Avatar?';
		$id = $this->_getParam ( 'avatar_id' );
		$this->view->avatar_id = $id;
		// Check post
		if ($this->getRequest ()->isPost ()) {
			$db = Engine_Db_Table::getDefaultAdapter ();
			$db->beginTransaction ();
			
			try {
				$avatar = Engine_Api::_ ()->getDbtable ( 'avatars', 'avatar' )->fetchRow ( array ('avatar_id = ?' => $id ) );
				$avatar_data = $avatar->toArray ();
				$avatar->delete ();
				
				$db->commit ();
				$file_dest = APPLICATION_PATH . '/application/modules/Avatar/externals/avatarcollections/' . $avatar_data ['avatarcollection_id'] . '/' . 'avatar_' . $avatar_data ['avatar_id'] . '.' . $avatar_data ['extension'];
				unlink ( $file_dest );
			} 

			catch ( Exception $e ) {
				$db->rollBack ();
				throw $e;
			}
			
			$this->_forward ( 'success', 'utility', 'core', array ('smoothboxClose' => 1, 'parentRefresh' => 2, 'messages' => array ('' ) ) );
		}
		
		// Output
		$this->renderScript ( 'etc/delete.tpl' );
	}
	
	public function uploadAvatarsAction() {
		$translate = Zend_Registry::get ( 'Zend_Translate' );
		try {
			if (! $this->getRequest ()->isPost ()) {
				throw new Engine_Exception ( 'Invalid request method' );
			}
			
			$values = $this->getRequest ()->getPost ();
			if (empty ( $values ['collection_id'] )) {
				throw new Engine_Exception ( 'Collection Id is not set.' );
			}
			if (empty ( $values ['Filename'] )) {
				throw new Engine_Exception ( 'No file' );
			}
			if (! isset ( $_FILES ['Filedata'] ) || ! is_uploaded_file ( $_FILES ['Filedata'] ['tmp_name'] )) {
				throw new Engine_Exception ( 'Invalid Upload or file too large' );
			}
			if (! preg_match ( '/\.(jpg|jpeg|gif|png)$/', strtolower ( $_FILES ['Filedata'] ['name'] ) )) {
				throw new Engine_Exception ( 'Invalid file type' );
			}
		} catch ( Exception $e ) {
			$this->_helper->json ( array ('status' => false, 'error' => $translate->_ ( $e->getMessage () ) ) );
			return;
		}
		$avatarsdb = Engine_Api::_ ()->getDbtable ( 'avatars', 'avatar' );
		$db = $avatarsdb->getAdapter ();
		$db->beginTransaction ();
		try {
			$avatar = $avatarsdb->createRow ();
			$suffix = strtolower ( end ( explode ( ".", $_FILES ['Filedata'] ['name'] ) ) );
			$save_values = array ('file_name' => basename ( $_FILES ['Filedata'] ['name'], '.' . $suffix ), 'extension' => $suffix, 'avatarcollection_id' => ( int ) $values ['collection_id'] );
			$avatar->setFromArray ( $save_values );
			$avatar->save ();
			$avatar_id = $avatar->getIdentity ();
			$file_dest = APPLICATION_PATH . '/application/modules/Avatar/externals/avatarcollections/' . $values ['collection_id'] . '/' . 'avatar_' . $avatar_id . '.' . $suffix;
			if (! @move_uploaded_file ( $_FILES ['Filedata'] ['tmp_name'], $file_dest ))
				throw new Engine_Exception ( 'Cann\'t save file.' );
			$db->commit ();
			$this->_helper->json ( array ('status' => true ) );
		} catch ( Exception $e ) {
			$db->rollback ();
			$this->_helper->json ( array ('status' => false, 'error' => $translate->_ ( 'Cann\'t save file.' ) ) );
			return;
		}
	}

}
